<template>
  <div class="main-pointSearch">
    <div class="layui-tab layui-tab-brief" lay-filter="test-handle">
      <ul class="layui-tab-title">
        <li class="layui-this" lay-id="search">查询</li>
        <li lay-id="result">显示结果</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div style="display:flex; padding: 15px 0; border-bottom: 1px solid #fff;">
            <div style="width:33%; text-align: center; ">
              <label class="btn btn-primary" style="margin: 3px 0; ">
                <input class="guanpoint-search-type" type="checkbox" value="ZY_JSPOINT"> 给水点
              </label>
              <br/>
              <label class="btn btn-primary" style="margin: 3px 0; ">
                <input class="guanpoint-search-type" type="checkbox" value="ZY_YSPOINT"> 雨水点
              </label>
              <br/>
              <label class="btn btn-primary" style="margin: 3px 0; ">
                <input class="guanpoint-search-type" type="checkbox" value="ZY_GDPOINT"> 电力点
              </label>
              <br/>
              <label class="btn btn-primary" style="margin: 3px 0; ">
                <input class="guanpoint-search-type" type="checkbox" value="ZY_LDPOINT"> 路灯点
              </label>
            </div>
            <div style="width:33%; text-align: center; ">
              <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                      @click="allSelect(1)">全选
              </button>
              <br/>
              <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                      @click="allSelect(-1)">全不选
              </button>
              <br/>
              <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                      @click="allSelect(0)">反选
              </button>
            </div>
          </div>
          <div class="layui-row" style="padding: 15px 0; border-bottom: 1px solid #fff;">
            <div class="layui-col-md6 layui-col-md-offset1">
              <input type="button" class="btn btn-primary" value="矩形" @click="drawRectangle"/>
              <input type="button" class="btn btn-primary" value="面" @click="drawPolygon"/>
              <input type="button" class="btn btn-primary" value="圆" @click="drawCircle()"/>
              <input type="button" class="btn btn-primary" value="清除" @click="clearDraw()"/>
            </div>
          </div>
        </div>
        <div class="layui-tab-item">
          <table
              id="table"
              data-toggle="table"
              data-height="550"
              data-width="430"
              data-search="true"
              data-pagination="true"
              style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap; color:#fff;"
          >
            <thead id="thead" style="color:#fff;">

            </thead>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
let from
// eslint-disable-next-line no-unused-vars
let count
// eslint-disable-next-line no-unused-vars
let dataTable = []
let $table
import fetchData from "@/components/js/fetchData";
import layersMap from "@/components/js/layerMap";
import {highLightForPointSearch} from "@/components/js/highLight";

export default {
  name: "pointSearch",
  components: {},
  data() {
    return {};
  },
  mounted() {

  },
  methods: {
    allSelect(flag) {
      let els = $('.guanpoint-search-type')
      if (flag == 1) {
        for (let index = 0; index < els.length; index++) {
          const element = els[index];
          element.checked = true
        }
      } else if (flag == -1) {
        $('.guanpoint-search-type').attr('checked', false)
      } else { // 反选
        for (let index = 0; index < els.length; index++) {
          const element = els[index];
          element.checked = !element.checked
        }
      }
    },
    hideLayerContent() {
      this.$emit('hidden')
    },
    showLayerContent() {
      this.$emit('show')
    },
    clearDraw() {
      console.log('---gdSearchClazz.clearDraw()')
      window.viewer.dadi.draw.clearDraw();
      from = null;
      // $table.bootstrapTable('destroy')
      $('#layerSelect').html('');
      // $('#thead').html('')
    },
    handleSearch() {
      let drawGeojson = window.viewer.dadi.draw.toGeoJSON()
      let els = $('.guanpoint-search-type')
      let pipelineTypes = []
      for (let index = 0; index < els.length; index++) {
        const element = els[index];
        if (element.checked) {
          pipelineTypes.push(element.value)
        }
      }

      if (pipelineTypes.length == 0) {
        // eslint-disable-next-line no-undef
        layui.layer.alert('至少选择一类管点进行查询！')
        return;
      }

      // 求from
      if (drawGeojson.features[0].properties.type === 'circle') {
        from = turf.buffer(turf.feature(drawGeojson.features[0].geometry), Number(drawGeojson.features[0].properties.style.radius) / 1000, {units: 'kilometers'})
      } else if (drawGeojson.features[0].properties.type === 'polygon') {
        from = turf.feature(drawGeojson.features[0].geometry)
      } else if (drawGeojson.features[0].properties.type === 'rectangle') {
        let geo = drawGeojson.features[0].geometry.coordinates.reduce(function (a, b) {
          a.splice(-1)
          b.splice(-1)
          return a.concat(b)
        })
        from = turf.bboxPolygon(geo)
      }

      let bianli = 0;
      let properties = [];
      pipelineTypes.forEach(async item => {
        bianli++;
        let mylayer = layersMap.find(l => l.pipelineType === item)
        if (mylayer) {
          const r = await fetchData(mylayer.url)
          r.features.forEach(fea => {
            // 空间筛选
            let to = turf.feature(fea.geometry)
            let withIntersect = turf.booleanIntersects(to, from);
            if (withIntersect) {
              properties.push({...fea.properties,})
            }
          })
        }
      })

      function refreshTable(tableArr) {
        $table = $('#table');
        let thead = `<tr>`
        Object.keys(tableArr[0]).forEach(key => {
          thead += `<th data-field="${key}">${key}</th>`
        })
        thead += `</tr>`
        $table.bootstrapTable('destroy')
        $('#thead').html(thead)
        $table.bootstrapTable({
          data: tableArr,
          onClickRow: function (row, $element) {
            console.log(row, $element)
            highLightForPointSearch(row)
          }
        })
        $table.bootstrapTable('refresh')
      }

      let timer = setInterval(() => {
        if (bianli === pipelineTypes.length) {
          window.clearInterval(timer)
          refreshTable(properties)
          layui.element.tabChange('test-handle', 'result'); // 切换到：标签3
        }
      }, 2000);

    },
    drawRectangle() {
      this.clearDraw();
      this.hideLayerContent()
      window.viewer.dadi.draw.startDraw({
        type: "rectangle",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        success: () => {
          this.handleSearch()
          this.showLayerContent()
        }
      });
    },
    drawPolygon() {
      this.clearDraw();
      this.hideLayerContent()
      window.viewer.dadi.draw.startDraw({
        type: "polygon",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        success: () => {
          this.handleSearch()
          this.showLayerContent()
        }
      });
    },
    drawCircle() {
      this.clearDraw();
      this.hideLayerContent()
      window.viewer.dadi.draw.startDraw({
        type: "circle",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        success: () => {
          this.handleSearch()
          this.showLayerContent()
        }
      });
    }
  },
  watch: {},
  computed: {},
  beforeDestroy() {
    this.clearDraw()
    let highLightLayer = window.viewer.dataSources.getByName('highLightLayer')[0]
    if(highLightLayer){
      highLightLayer.entities.removeAll()
    }
  },
}
</script>

<style scoped>
.main-pointSearch {
  position: relative;
  height: 100%;
  width: 100%;
}
</style>
